import mechanize
import re
import time
from datetime import datetime
import sys
import getopt
from calculate import calculate

def initBrowser():
    print "Initialize Browser"
    br = mechanize.Browser(factory=mechanize.RobustFactory())
    br.set_handle_robots(False)
    return br

def login(br):
#######  Login  #######
    print "Login"
    br.open("https://tools.cleanpowerfinance.com/user/login")
    br.select_form("loginform")
    br["username"]="kate@completesolar.com"
    br["password"]="solar123solar"
    response1 = br.submit()
    return br

def getUserPage(br):
    print "Get Helios Page"
#######  Search for Test Customer  #######
    br.select_form(nr=1)
    br["keyword"]="Helios"
    response = br.submit()
#######  Manage the customers settings  #######
    myLink = None
    for link in br.links(url_regex="estimate.php*"):
        #print link
        myLink = link
    response = br.follow_link(myLink)
    return br

def gotoScreen(br, screen):
    print "going to "+screen
    screens = ["summary", "location", "energy", "equip", "analysis", "review","proposal"]
    br.select_form(nr=0)
    br.find_control("nextpage").readonly = False
    br["nextpage"] = screen
    br.submit()
    return br

def fillLocation(br, azimuth, shading):
#######  Go to the correct screen  #######
    print "Filling Location Tab"
    br.select_form(nr=0)
    #print response.read()
    br.find_control("nextpage").readonly = False
    br.find_control("subpage").readonly = False
    br["nextpage"]="energy"
    br["subpage"]="location"
    response = br.submit()
    br.select_form(nr=0)
    #print br["siteassessment"]
    br["siteassessment"] = ["0"]
    br["cutility1"] = ["291"]
    br["usetou"] = ["0"]
    br["cheight1"] = "500"
    br["clength1"] = "500"
    br["inoct1"] = ["44"]
    br["tilt1"] = ["20"]
    br["azimuth1"] = [str(azimuth)]
    br["soiling"] = ["2"]
    br["shade11"] = str(shading)
    br["shade12"] = str(shading)
    br["shade13"] = str(shading)
    br["shade14"] = str(shading)
    br["shade15"] = str(shading)
    br["shade16"] = str(shading)
    br["shade17"] = str(shading)
    br["shade18"] = str(shading)
    br["shade19"] = str(shading)
    br["shade110"] = str(shading)
    br["shade111"] = str(shading)
    br["shade112"] = str(shading)
    br.submit();
    return br

def fillEnergy(br):
    print "Filling Energy Tab"
    br.select_form(nr=0)
    br.find_control("nextpage").readonly = False
    br["nextpage"]="equip"
    br["presolarrate1"] = ["4042"]
    br["euse1"] = "2000"
    br["euse2"] = "2000"
    br["euse3"] = "2000"
    br["euse4"] = "2000"
    br["euse5"] = "2000"
    br["euse6"] = "2000"
    br["euse7"] = "2000"
    br["euse8"] = "2000"
    br["euse9"] = "2000"
    br["euse10"] = "2000"
    br["euse11"] = "2000"
    br["euse12"] = "2000"
    response = br.submit()
    return br

def fillEquip(br):
    print "Filling Equip Tab"
    br.select_form(nr=0)
    br.find_control("nextpage").readonly = False
    br["nextpage"]="analysis"
    br["collectorid"] = ["2352"]
    br["inverterid"] = ["917"]
    br["crate1"]=["4042"]
    br["incent2615"] = ["1"]
    response = br.submit()
    return br

def fillAnalysis(br, panels, kwh, designFactor):
    print "Filling Analysis Tab"
    br.select_form(nr=0)
    br.find_control("nextpage").readonly = False
    br["nextpage"] = "review"
    br["nummod1"] = panels
    br["kwh1"] = kwh
    br["invid_a1"] = ["917"]
    br["numinverter1"] = panels
    br["dsnfactor1"] = designFactor
    response = br.submit()
    return (br, response)

def fetchData(outputFile, br, azimuth="90",shading="100", instThisYear=False):
    print "Fetching Data"
    panelInverterCounts = ["11", "22", "30", "44"]
    #panelInverterCounts = ["11","22"]
    systemSizes = {}
    systemSizes["11"] = "2.53"
    systemSizes["22"] = "5.06"
    systemSizes["30"] = "6.9"
    systemSizes["44"] = "10.12"
    designFactors = {}
    designFactors["90", "100"] = "85.673"
    designFactors["90", "93"] = "78.832"
    designFactors["90", "85"] = "72.831"
    designFactors["180", "100"] = "97.297"
    designFactors["180", "93"] = "89.513"
    designFactors["180", "85"] = "82.693"
    designFactors["270", "100"] = "96.083"
    designFactors["270", "93"] = "88.405"
    designFactors["270", "85"] = "81.676"
#######  We should be on the customers screen here  #######
    br = fillLocation(br, azimuth, shading)
#######  We should be on the Energy screen here  #######
    br = fillEnergy(br)
#######  We should be on the Equip screen here  #######    
    br = fillEquip(br)
#######  We should be on the Analysis screen here  #######
    for panelCount in panelInverterCounts:
        systemSize = systemSizes[panelCount]
        designFactor = designFactors[azimuth, shading]
        (br, response) = fillAnalysis(br, panelCount, systemSize, designFactor)
#######  We should be on the Review screen here  #######
        html = response.read()
        csi = html.split('<td align="right" class="rebate_original_postcontract" original="')
        csi = csi[1]
        csi = csi.split(">")[1]
        csi = csi.split("<")[0]
        csi = csi.replace(",","")
        print "CSI = " + csi
        production = html.split('<td align="right">Estimated Annual Production</td>')[1]
        production = production.split("</td>")[0]
        production = production.replace('<td align="left">',"")
        production = production.strip()
        production = production.replace(",","")
        print "production =" +production
        br.select_form(nr=0)
        br.find_control("nextpage").readonly = False
        br["nextpage"]="proposal"
        if instThisYear == True:
            instThisYear = "1"
        else:
            instThisYear = "0"
        annualIncreases = ["0","1","2","2.9","3.5"]
        initialPayments = ["0", "250", "1000", "2000", "5000"]
        
        #annualIncreases = ["2","2.9"]
        #initialPayments = ["250","2000"]
        
        grossMarginValues = {}
        grossMarginValues["11"] = ["21","28","32","36","40","44","46"]
        #grossMarginValues["11"] = ["21"]
        grossMarginValues["22"] = ["17","21","32","38","42","44","46"]
        #grossMarginValues["22"] = ["21", "32"]
        grossMarginValues["30"] = ["17","21","32","38","42","45","47"]
        grossMarginValues["44"] = ["17","21","32","38","42","46","48"]
        for initialPayment in initialPayments:
            for escalator in annualIncreases:
                for gmv in grossMarginValues[panelCount]:
                    data = calculate(br, gmv, escalator, initialPayment, instThisYear)
                    grossMarginActual = data[0]
                    systemPrice = data[1].replace(",","")
                    ppkwh = data[2].replace(",","")
                    initialPayment = data[3].replace(",","")
                    preSolarMonthlyCost = data[4].replace(",","")
                    postSolarMonthlyCost = data[5].replace(",","")
                    finPaymentPlusUtility = data[6].replace(",","")
                    monthlySavings = data[7].replace(",","")
                    payback = data[8].replace(",","")
                    financePayment = data[6].split(" ")
                    financePayment = financePayment[0]
                    financePayment = financePayment.replace("($","").replace(",","")
                    print azimuth + " " + shading + " " + initialPayment
                    outputFile.write(systemSize+","+ initialPayment+","+
                                     escalator+","+ gmv+","+systemPrice+","+
                                     azimuth+","+ shading+","+
                                     designFactor+","+ csi+","+
                                     production+","+ ppkwh+","+
                                     financePayment+"\n\r")
                    print "record complete\n"
                    time.sleep(1)
        response = br.open("https://tools.cleanpowerfinance.com/secure/dashboard.php")
        br = getUserPage(br)
        br = gotoScreen(br, "analysis")

    #link = br.find_link(url="javascript:processform('location')")
    #br.follow_link(link)
    #for link in br.links():
    #    print link
    #print br.title()
    #print response1.geturl()
    #print response1.info()

def usage():
   print "FILL THIS IN LATER"

def main(argv):
  try: 
    opts, args = getopt.getopt(argv, "th",["thisYear", "help"])
  except getopt.GetoptError:
    usage()
    sys.exit(2)
  print "Checking inputs"
  thisYear = False
  for opt, arg in opts:
    if opt in ("-h", "--help"):
      usage()
      sys.exit()
    elif opt in ("-s", "--site="):
      site = arg
    elif opt in ("-t", "--thisYear"):
      thisYear = true
    else:
      print "unhandled option"
      sys.exit(2)
  br = initBrowser()
  br = login(br)
  br = getUserPage(br)
  now = str(datetime.now())
  print "output\\"+now+".csv"
  #outputFile = open("output\\"+now+".csv",'w')
  outputFile = open("output\\test.csv",'w')
  outputFile.write("System Size,Down,Escalator,Gross Margin,Gross Price,Azimuth,Shade,Design Factor,CSI,Production,PPKWH,Pmt/mo\n")
  azimuthVals = ["90","180","270"]
  #azimuthVals = ["90", "180"]
  shadingVals = ["100","93","85"]
  #shadingVals = ["100","93"]
  for azimuthVal in azimuthVals:
      for shade in shadingVals:
          print "starting with Values (azimuth, shading): ("+azimuthVal+","+shade+")"
          results = fetchData(outputFile, br, azimuthVal,shade, thisYear)
  print "Finished: Closing File"
  outputFile.close()
  
if __name__=="__main__":
  main(sys.argv[1:])
